package com.kfm.servlet;

import com.kfm.util.MailUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/mail")
public class MailServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 发送邮件 2. 存储cookie  3.跳转到页面
        String code = MailUtils.sendEmail("wxlp0323@gmail.com");
        Cookie cookie = new Cookie("code", code);
        resp.addCookie(cookie);
        req.getRequestDispatcher("send.html").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        // 解析请求获取输入的验证码以及cookie中的验证码 作比对
        // 1. 获取请求参数 输入的验证码
        String inputCode = req.getParameter("code");
        // 2. 获取cookie中存储的验证码信息
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            // 获取的cookie对象的key是存储的cookie的key
            if ("code".equals(cookie.getName())) {
                String code = cookie.getValue();
                if (inputCode != null && inputCode.equals(code)) {
                    System.out.println("验证码正确");
                    resp.getWriter().write("<h3 style='color:green;'>验证码输入正确</h3>");
                    return;
                }
            }
        }
        System.out.println("验证码错误");
        resp.getWriter().write("<h3 style='color:red;'>验证码错误！</h3>");
    }
}
